package cn.com.dcsgo.controller;

import cn.com.dcsgo.common.Result;
import cn.com.dcsgo.constants.CoreConstant;
import cn.com.dcsgo.domain.dto.UserLoginDTO;
import cn.com.dcsgo.domain.po.SysUser;
import cn.com.dcsgo.domain.vo.UserLoginVO;
import cn.com.dcsgo.enums.ResultEnums;
import cn.com.dcsgo.service.SysUserService;
import cn.com.dcsgo.utils.ServletUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.util.DigestUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;
import java.util.List;

/**
 * UserLoginController
 *
 * @author Dcsgo
 * @since 20/5/2025 下午 3:22
 */
@Slf4j
@Tag(name = "用户登录")
@RestController
@RequiredArgsConstructor
public class UserLoginController extends BaseController {
    private final SysUserService sysUserService;

    @Operation(summary = "退出登录")
    @GetMapping("logout")
    public Result<Serializable> logout() {
        // 让 session 失效
        ServletUtils.getSession().invalidate();
        return new Result<>(ResultEnums.SUCCESS);
    }

    @Operation(summary = "登录")
    @PostMapping(CoreConstant.LOGIN_URL)
    public Result<String> login(@Validated UserLoginDTO userLoginDTO) {
        // 得到正确的验证码
        Object rightCaptcha = ServletUtils.getSession().getAttribute(CoreConstant.CAPTCHA_KEY);
        Assert.notNull(rightCaptcha, "验证码未生成");

        if (!rightCaptcha.toString().equals(userLoginDTO.getCode())) {
            return new Result<>(ResultEnums.ERROR.getCode(), "验证码不正确");
        }

        // 效验用户名与密码
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();
        // 将 password 加密(数据库中存储的是md5加密后的密码)
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        SysUser user = sysUserService.getOne(username, password);
        if (user == null) {
            return new Result<>(ResultEnums.USER_PASSWORD_ERROR);
        }

        // 把用户信息添加到 session 中
        user.setPassword(null);
        log.debug("user:{}", user);
        ServletUtils.getSession().setAttribute(CoreConstant.SESSION_KEY, user);

        return new Result<>(ResultEnums.SUCCESS);
    }

    @Operation(summary = "获取用户信息")
    @GetMapping("getUserInfo")
    Result<UserLoginVO> getUserInfo() {
        SysUser user = getCurrentUser();
        Assert.notNull(user, "用户未登录");

        UserLoginVO userLoginVO = new UserLoginVO();

        // 获取并封装用户所在部门名称和直属领导名
        user = sysUserService.getOneWithDeptNameAndLeaderName(user.getUserId());
        Assert.notNull(user, "用户不存在");
        userLoginVO.setUser(user);

        List<String> permissions;
        // 获取并封装用户权限信息
        if (user.getUserType().equals(CoreConstant.USER_TYPE_ADMIN)) {
            // 管理员直接返回所有权限
            permissions = sysUserService.getAllPermission();
        } else {
            // 普通用户正常查询
            permissions = sysUserService.getPermissions(user.getUserId());
        }
        userLoginVO.setPermissions(permissions);
        // 将权限添加到 session 中用于后端的权限校验
        ServletUtils.getSession().setAttribute(CoreConstant.PERMISSIONS_KEY, permissions);

        return new Result<>(ResultEnums.SUCCESS, userLoginVO);
    }
}
